<template>
  <div>
    <el-form :model="basicInfo" :rules="rules" ref="basicInfo" class="demo-ruleForm">
      <div class="detail-info" style="margin-top: 50px">
        <div class="form-item">
          <h4>基本信息</h4>
            <el-row>
            <el-col :span="12">
              <el-form-item label="所属分公司" label-width="180px" required>
                <el-select v-if="!brachDisabled" v-model="basicInfo.branchId" :disabled="brachDisabled"
                @change="getDeptList" @visible-change="visibleChange" style="width:200px" placeholder="分公司">
                  <el-option v-for="(item, index) in this.branchList" :value="item.branch_Id" :label="item.branch_Name" :key="index"></el-option>
                </el-select>
                <el-input v-if="brachDisabled" v-model="showBranch" :disabled="brachDisabled" style="width:200px"></el-input>
              </el-form-item>
              <el-form-item label="所属部门" label-width="180px" prop="dept" required>
                <el-select v-if="!brachDisabled" v-model="basicInfo.dept" :disabled="brachDisabled" placeholder="所属部门" style="width:195px">
                  <el-option v-for="(item, index) in this.deptList" :value="item.org_id" :label="item.org_name" :key="index"></el-option>
                </el-select>
                <el-input v-if="brachDisabled" v-model="this.showDept" disabled style="width:195px"></el-input>
              </el-form-item>
              <el-form-item label="促销费用" label-width="180px" prop="cxcost">
                <!-- <el-input v-model="basicInfo.cxcost" style="width:200px"></el-input> -->
                <el-select v-model="basicInfo.cxcost" @change="handleChangeSalesCosts" placeholder="请选择促销费用" style="width:220px" :loading="saleCostLoading">
                  <el-option v-for="(item, index) in salesCostsList" :key="index" :label="item.promotionName" :value="item.id.toString()" ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="this.selectSalesCosts.type === 2 || this.selectSalesCosts.type === ''"
              label="供应商占比" label-width="180px" prop="gysproportion" required>
                <el-input v-model="basicInfo.gysproportion" style="width:200px"></el-input>%
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="批次名称" label-width="180px" prop="pcname">
                <el-input v-model="basicInfo.pcname" style="width:220px"></el-input>
              </el-form-item>
              <el-form-item label="客资类型" label-width="180px" prop="usertype">
                <el-select v-model="basicInfo.usertype" style="width:220px" placeholder="客资类型" :loading="customerTypeLoading">
                  <!-- <el-option value="1" label="普通超市"></el-option> -->
                  <el-option v-for="(item, index) in customerTypeList"
                  :key="index"
                  :label="item.name"
                  :value="item.id.toString()"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="活动起止时间" label-width="180px" prop="startStopTime" required >
                <el-date-picker
                  :editable="false"
                  v-model="basicInfo.startStopTime"
                  type="daterange" placeholder="活动起止时间"
                  value-format="yyyy-MM-dd"
                  @change="daterangeFormat" style="width:220px"
                  :picker-options="pickerExpirationDate"
                 ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- </el-form> -->
        </div>
      </div>
      <div class="detail-info" style="margin-top: 50px">
        <div class="form-item">
          <h4>优惠券信息</h4>
          <el-button type="primary" @click="handleChooseCoupon">选择优惠券</el-button>
          <el-table :data="redeemCodeDetails" border style="margin-top:20px;width: 100%">
            <el-table-column label="优惠券ID" prop="qid" align="center" width="80"></el-table-column>
            <el-table-column label="优惠券名称" prop="ticketName" align="center" width="100"></el-table-column>
            <el-table-column label="类型" align="center" width="100">
              <template scope="scope">
                <span v-if="scope.row.qtype === '1'">现金券</span>
                <span v-if="scope.row.qtype === '2'">满减券</span>
                <span v-if="scope.row.qtype === '3'">实物券</span>
                <span v-if="scope.row.qtype === '4'">品牌现金券</span>
                <span v-if="scope.row.qtype === '6'">品类券</span>
              </template>
            </el-table-column>
            <el-table-column label="面值" prop="ticketCost" align="center" width="80"></el-table-column>
            <el-table-column label="满多少元可用" prop="ticketPrice" align="center" width="100"></el-table-column>
            <el-table-column label="满多少件可用" prop="numLimit" align="center" width="100"></el-table-column>
            <el-table-column label="有效期类型" align="center" width="120">
              <template scope="scope">
                <el-select v-model="scope.row.expirationType" placeholder="有效期类型" @change="changeExpirationType($event, scope.row)">
                  <el-option value="1" label="时间段"></el-option>
                  <el-option value="2" label="截止时间"></el-option>
                  <el-option v-if="selectSalesCosts.type === 1" value="3" label="天数"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="有效期" align="center" min-width="225">
              <template scope="scope">
                <el-date-picker :editable="false" :clearable="false"
                v-model="scope.row.beginDate" v-if="scope.row.expirationType==='1'"
                @change="valueToTable(scope.row, 'beginDate', $event, scope.$index)"
                placeholder="开始时间" style="width:45%"
                :picker-options="pickerOptions" value-format="yyyy-MM-dd"
                ></el-date-picker>
                <el-date-picker :editable="false" :clearable="false"
                v-model="scope.row.endDate" v-if="scope.row.expirationType==='1' || scope.row.expirationType==='2'"
                @change="valueToTable(scope.row, 'endDate', $event, scope.$index)"
                placeholder="结束时间" style="width:45%"
                :picker-options="pickerOptions" value-format="yyyy-MM-dd"
                ></el-date-picker>
                <el-input v-model="scope.row.daynum" v-if="scope.row.expirationType==='3'"
                @blur="valueToTable(scope.row, 'daynum', $event, scope.$index)"
                style="width:45%" placeholder="请输入天数"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="每人/张数" align="center" width="100">
              <template scope="scope">
                <el-input v-model="scope.row.num"
                @blur="valueToTable(scope.row, 'num', $event, scope.$index)"
                placeholder="每人/张数"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="建券人" prop="createUser" align="center" width="80"></el-table-column>
            <el-table-column label="操作" align="center" width="60">
              <template scope="scope">
                <el-button type="text" size="small" @click="deleteCoupon('优惠券', redeemCodeDetails, chooseCouponTableList, scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-dialog title="选择优惠券" :visible.sync="couponDialog">
            <el-row style="margin-top:20px">
              <!-- <el-form :model="chooseCouponInfo"> -->
                <el-col :span="6" style="margin-right:10px">
                  <el-form-item label="券类型">
                    <el-select v-model="chooseCouponInfo.ticketType" placeholder="请选择券类型" style="width:130px">
                      <el-option v-for="(item, index) in ticketTypeGroup"
                      :key="index"
                      :value="item.ticketType.toString()"
                      :label="item.tname"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7" style="margin-right:10px">
                  <el-form-item label="优惠券名称">
                    <el-input v-model="chooseCouponInfo.tname" placeholder="优惠券名称" style="width:130px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="7" style="margin-right:10px">
                  <el-form-item label="优惠券ID">
                    <el-input v-model="chooseCouponInfo.id" placeholder="优惠券ID" style="width:130px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="3" >
                  <el-button type="primary" style="float:right" @click="searchCoupon('优惠券')">搜索</el-button>
                </el-col>
                <el-table :data="chooseCouponTableList" border v-loading="searchLoading">
                  <el-table-column prop="qid" label="优惠券ID" align="center"></el-table-column>
                  <el-table-column prop="ticketName" label="优惠券名称" align="center"></el-table-column>
                  <el-table-column label="类型" align="center">
                    <template scope="scope">
                      <span v-if="scope.row.qtype === '1'">现金券</span>
                      <span v-if="scope.row.qtype === '2'">满减券</span>
                      <span v-if="scope.row.qtype === '3'">实物券</span>
                      <span v-if="scope.row.qtype === '4'">品牌现金券</span>
                      <span v-if="scope.row.qtype === '6'">品类券</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="ticketCost" label="面值" align="center"></el-table-column>
                  <el-table-column prop="ticketPrice" label="满多少元可用" align="center"></el-table-column>
                  <el-table-column prop="numLimit" label="满多少件可用" align="center" width="100"></el-table-column>
                  <el-table-column prop="remark" label="备注" align="center"></el-table-column>
                  <el-table-column label="操作" align="center">
                    <template scope="scope">
                      <el-button v-if="scope.row.operation === 0" @click="addCode(scope.row, chooseCouponTableList[scope.$index])" type="text">添加</el-button>
                      <el-button v-if="scope.row.operation === 1" @click="recallCode(scope.row, scope.row.qtype, scope.row.qid)" type="text">撤回</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                  @current-change="handleCurrentChange"
                  :page-size="Number(chooseCouponInfo.pageSize)"
                  layout="total, prev, pager, next"
                  :total="Number(chooseCouponInfo.total)"
                  style="padding-top:10px;text-align: right;">
                </el-pagination>
            </el-row>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="couponDialogTrue">确 定</el-button>
            </div>
          </el-dialog>
        </div>
      </div>
      <div class="detail-info">
        <div class="form-item" style="margin-bottom:0">
          <h4>系统通知</h4>
          <el-row>
            <el-input style="width:400px" v-model="basicInfo.messageTitle" placeholder="请输入标题"></el-input>
          </el-row>
          <el-row>
            <el-input style="width:400px" v-model="basicInfo.messageContent" type="textarea" placeholder="请输入内容"></el-input>
          </el-row>
        </div>
      </div>
      <div class="detail-info">
        <div class="form-item" style="margin-bottom:0">
          <h4>备注</h4>
          <el-input style="width:400px" type="textarea" placeholder="请输入备注" v-model="basicInfo.remark"></el-input>
        </div>
      </div>
      <div style="margin: 20px auto 20px; width: 20%">
        <el-button @click="onSubmit(2, 'basicInfo')" type="success">提交</el-button>
        <el-button @click="onSubmit(1, 'basicInfo')" type="warning">暂存</el-button>
        <el-button @click="cancel(menuId, 1)" type="danger">取消</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
  import { getInfo, activity } from '../../../../config/proxy.js'
  import { mapState } from 'vuex'
  import mixins from '../../../../components/mixins.vue'
  import moment from 'moment'
  export default {
    mixins: [mixins],
    data () {
      var self = this
//      var nameTest = (rule, value, callback) => { // 批次名称验证
//        if (!value) {
//          return callback(new Error('请输入批次名称'))
//        } else {
//          if (value.length > 16) {
//            callback(new Error('您输入的名称过长!'))
//          } else {
//            callback()
//          }
//        }
//      }
      var checkGysproportion = (rule, value, callback) => { // 验证供应商占比
        var text = rule.field === 'gysproportion' ? '供应商占比' : '充值金额'
        if (!value) {
          return callback(new Error(text + '不能为空'))
        } else {
          var reg = /^[0-9]\d*$/
          if (reg.test(value)) {
            value = value.toString()
            if (value.indexOf(0) === 0 && value.length > 1) {
              callback(new Error('不能以0开头'))
            }
            callback()
          } else {
            callback(new Error('供应商占比必须正整数'))
          }
        }
      }
      return {
        pickerExpirationDate: { // 有效期类型禁用时间段
          disabledDate (time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        pickerOptions: {
          disabledDate (time) {
            return time.getTime() < new Date(self.selectSalesCosts.stime).getTime() || time.getTime() > new Date(self.selectSalesCosts.etime).getTime()
          }
        }, // 禁用时间段
        basicInfo: {
          branchId: '',
          dept: '',
          cxcost: '', // 促销费用
          startDate: '', // 开始时间
          overDate: '', // 结束时间
          startStopTime: '', // 兑换截止日期
          gysproportion: '', // 供应商补差占比
          pcname: '', // 批次名称
          usertype: '1', // 客资类型
          remark: '', // 备注
          messageTitle: '', // 标题
          messageContent: '' // 通知内容
        },
        // pageLoading: false,
        showBranchName: '', // 页面展示的公司名称
        showDeptName: '', // 页面展示的部门名称
        saleCostLoading: true, // 促销费用加载
        customerTypeLoading: true, // 客资类型加载
        salesCostsList: [], // 促销费用数组
        selectSalesCosts: {}, // 选中的促销费用
        customerTypeList: [], // 客资类型
        redeemCodeDetails: [],
        validityType: '2', // 有效期类型
        validity: '', // 有效期
        creatTotal: '', // 生成总数
        tableTime: '',
        tableTimeRange: '',
        remark: '', // 备注
        chooseCouponTableList: [], // 优惠券弹框table list
        couponDialog: false, // 优惠券弹框
        couponValid: false, // 优惠券验证
        searchLoading: false, // 搜索优惠券加载
        chooseCouponInfo: { // 选择优惠券条件
          id: '', // 优惠券id
          ticketType: '1', // 优惠券类型
          tname: '', // 优惠券名称
          page: '1',
          pageSize: '20',
          total: 0
        },
        ticketTypeGroup: [],
        pageData: {
          pageSize: 10,
          page: 1
        },
        total: '',
        isCreateOrUpdate: '',
        text: '',
        menuId: '',
        // subDisable: false,
        rules: {
          dept: [ // 促销费用
            {required: true, type: 'number', message: '请选择所属部门', trigger: 'change'}
          ],
          cxcost: [ // 促销费用
            {required: true, message: '请选择促销费用', trigger: 'change'}
          ],
          usertype: [ // 客资类型
            {required: true, message: '请选择客资类型', trigger: 'change'}
          ],
          gysproportion: [ // 供应商占比
            {validator: checkGysproportion, trigger: 'blur'}
          ],
          pcname: [ // 批次名称
            {required: true, message: '请输入批次名称', trigger: 'blur'},
            { min: 0, max: 16, message: '长度不能超过16个字符', trigger: 'blur' }
          ],
          startStopTime: [ // 截止日期
            {type: 'array', required: true, message: '请选择活动起止日期', trigger: 'change'}
          ]
        },
        showBranch: '',
        showDept: '',
        newBranchId: '',
        createBranchId: '',
        brachDisabled: false,
        deptList: [],
        visible: false
      }
    },
    methods: {
      getDeptList (val) { // 获取部门
        console.log(this.visible)
        this.searchSalesCosts()
        if (this.visible === true) {
          console.log('aaa')
          this.basicInfo.dept = ''
          this.basicInfo.cxcost = ''
        }
        var _data = {}
        var self = this
        setTimeout(() => {
          console.log(self.branchList)
          self.branchList.forEach(element => {
            if (val === element.branch_Id) {
              console.log(val === element.branch_Id)
              _data.orgId = element.org_id
              self.newBranchId = element.org_id
            }
          })
          console.log(_data)
          if (JSON.stringify(_data) === '{}') {
            return
          } else {
            getInfo.department(_data, (res) => {
              console.log(res)
              if (res.message === 'ok') {
                if (val === 1) {
                  self.deptList = []
                  res.content.forEach(element => {
                    if (element.org_name.indexOf('公司') === -1) {
                      self.deptList.push(element)
                    }
                  })
                  self.matchDept()
                } else {
                  self.deptList = res.content
                  self.matchDept()
                }
              } else {
                self.message(res.message, 'error')
              }
            })
          }
        }, 500)
      },
      matchDept () { // 匹配 当前登录人的部门与部门列表
        console.log(this.deptList)
        for (let index = 0; index < this.deptList.length; index++) {
          const element = this.deptList[index]
          console.log(Number(this.basicInfo.dept) === Number(element.org_id))
          console.log(Number(this.basicInfo.dept), Number(element.org_id))
          if (Number(this.basicInfo.dept) === Number(element.org_id)) {
            return
          } else {
            if (index === this.deptList.length - 1) {
              this.basicInfo.dept = ''
            }
          }
        }
      },
      visibleChange (a) {
        console.log(a)
        this.visible = a
      },
      searchCustomerType () { // 查询客资类型
        var _data = ''
        getInfo.client(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.customerTypeList = res.content.content
            this.customerTypeLoading = false
          }
        })
      },
      searchSalesCosts () { // 查询促销费用
        var _data = {
          branchId: this.basicInfo.branchId,
          activityType: '-1'
        }
        activity.cxfy.allList(_data, (res) => {
          // console.log(res)
          if (res.message === 'ok') {
            this.salesCostsList = res.content
            this.saleCostLoading = false
            // this.pageLoading = false
            // if (id) {
            //   this.searchDetail(id)
            // }
          }
        })
      },
      handleChangeSalesCosts (val) { // 选择促销费用
        for (var index = 0; index < this.salesCostsList.length; index++) {
          var element = this.salesCostsList[index]
          if (element.id === Number(val)) {
            if (element.promotionType === 1) {
              this.selectSalesCosts = {
                type: element.promotionType,
                stime: '',
                etime: ''
              }
            } else {
              this.selectSalesCosts = {
                type: element.promotionType,
                stime: this.timeDeltSecond(element.promotionBeginTime),
                etime: this.timeDeltSecond(element.promotionEndTime)
              }
            }
          }
        }
      },
      searchDetail (row) { // 查询详情
        // console.log(row)
        activity.yhqhd.zcfq.detail({id: row.id}, (res) => {
          console.log(res, '详情')
          if (res.message === 'ok') {
            // this.pageLoading = false
            this.creatRedeemCodeDetail(res.content)
            this.basicInfo.branchId = res.content.branchId // 创建时公司是返回的公司id
            this.showBranch = res.content.branchName // 创建时公司是返回的公司名称
            this.basicInfo.dept = res.content.dept // 创建时公司是返回的部门id
            this.showDept = res.content.deptName // 创建时公司是返回的部门名称
            this.createBranchId = this.branchOrgId // 创建时创建人新公司ID
            this.searchCustomerType()
            this.$store.dispatch('pageLoading', false)
          } else {
            this.message('查看详情失败', 'error')
            this.$store.dispatch('pageLoading', false)
          }
        })
      },
      handleChooseCoupon () { // 选择优惠券按钮
        // console.log('选择优惠券弹框')
        this.couponDialog = true
        this.searchCodeType()
      },
      searchCodeType () { // 查询券类型
        var _data = ''
        getInfo.couponType(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.ticketTypeGroup = res.content
          }
        })
      },
      searchCoupon (text) { // 查询优惠券
        // console.log('查询优惠券')
        this.searchLoading = true
        var _dataCode = this.chooseCouponInfo
        _dataCode.branchId = this.basicInfo.branchId
        _dataCode.departmentId = this.basicInfo.dept
        _dataCode.bid = this.newBranchId
        // delete _dataCode.total
        console.log(_dataCode)
        getInfo.couponList(_dataCode, (res) => {
          if (res.message === 'ok') {
            console.log('优惠券数组')
            // console.log(res)
            this.searchLoading = false
            if (res.content.content !== null) {
              this.chooseCouponTableList = []
              for (var k = 0; k < res.content.content.length; k++) {
                var eleCode = res.content.content[k]
                this.chooseCouponTableList.push({
                  'qid': eleCode.id, // 券id
                  'ticketName': eleCode.tname, // 券名称
                  'qtype': this.chooseCouponInfo.ticketType, // 券类型
                  'ticketCost': eleCode.tcost !== null ? eleCode.tcost : '', // 面值
                  'ticketPrice': eleCode.fulluse !== null ? eleCode.fulluse : '', // 满多少可用
                  'numLimit': eleCode.numLimit !== null ? eleCode.numLimit : '', // 满多少件可用
                  'remark': eleCode.remark,
                  'operation': 0,
                  'phpTicketId': eleCode.phpId
                })
                console.log(eleCode)
              }
              this.chooseCouponInfo.total = res.content.count
              this.chooseCouponInfo.page = res.content.page
              this.matchOperation(text, this.chooseCouponTableList, this.redeemCodeDetails)
            } else {
              this.chooseCouponTableList = []
            }
          }
        })
      },
      matchOperation (text, arr1, arr2) { // 查询时 匹配优惠券数组 和 已选则优惠券数组 显示 添加或撤回
        console.log(arguments)
        for (var i = 0; i < arr1.length; i++) {
          var allEle = arr1[i]
          if (arr2.length === 0) {
            arr1[i].operation = 0
          } else {
            for (var k = 0; k < arr2.length; k++) {
              var selectEle = arr2[k]
              if (text === '优惠券') {
                if (Number(allEle.qid) === Number(selectEle.qid) && Number(allEle.qtype) === Number(selectEle.qtype)) {
                // if (Number(allEle.ticketId) === Number(selectEle.ticketId) && Number(allEle.ticketName) === Number(selectEle.ticketName)) {
                  // console.log('aaaa')
                  arr1[i].operation = 1
                }
              } else if (text === '商品') {
                if (Number(allEle.productId) === Number(selectEle.productId)) {
                  // console.log('aaaa')
                  arr1[i].operation = 1
                }
              }
            }
          }
        }
      },
      addCode (row, data) { // 添加优惠券
        var newRow = {
          num: '',
          beginDate: '',
          createUser: this.userName,
          daynum: '',
          endDate: '',
          expirationType: '1',
          id: '',
          pid: '',
          qid: row.qid,
          qtype: row.qtype,
          ticketCost: row.ticketCost,
          ticketName: row.ticketName,
          ticketPrice: row.ticketPrice,
          numLimit: row.numLimit,
          ticketType: '',
          phpTicketId: row.phpTicketId
        }
        this.redeemCodeDetails.push(newRow)
        data.operation = 1
      },
      recallCode (row, type, id) { // 撤回
        console.log(arguments)
        for (var i = 0; i < this.redeemCodeDetails.length; i++) {
          var element = this.redeemCodeDetails[i]
          if (Number(element.qid) === Number(id) && Number(element.qtype) === Number(type)) {
            this.redeemCodeDetails.splice(i, 1)
          }
        }
        row.operation = 0
      },
      handleCurrentChange (val) { // 分页
        this.chooseCouponInfo.page = val
        this.searchCoupon('优惠券', this.chooseCouponTableList, this.redeemCodeDetails)
      },
      couponDialogTrue () { // 选择优惠券弹框确认按钮
        this.couponDialog = false
      },
      changeExpirationType (val, row) {
        // row.beginDate = ''
        // row.endDate = ''
        // row.daynum = ''
      },
      valueToTable (row, name, val, index) { // 有效期类型赋值
        if (val && val !== '') {
          if (row.expirationType === '1') {
            row[name] = val
            if (row.beginDate !== '' && row.endDate !== '') {
              if (new Date(row.beginDate) <= new Date(row.endDate)) {
              } else {
                console.log(row)
                this.message('结束时间不能小于开始时间', 'error')
                row[name] = ''
              }
            }
          } else if (row.expirationType === '2') {
            row[name] = val
          } else if (row.expirationType === '3') {
            row[name] = val
          }
          if (name === 'daynum' || name === 'num') {
            val = val.srcElement.value
            var text = name === 'daynum' ? '天数' : '每人张数'
            var re = /^[1-9]\d*$/
            if (re.test(val)) {
              row[name] = val
            } else {
              this.message('第' + (index + 1) + '行' + text + '格式错误，请输入正整数！', 'error')
              row[name] = ''
            }
          }
        }
      },
      deleteCoupon (text, arr, arr2, index, row) { // 删除优惠券
        // console.log(index)
        this.$confirm('您确定要删除该条优惠券信息吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.redeemCodeDetails.splice(index, 1)
          this.message('删除成功', 'success')
          for (var i = 0; i < arr2.length; i++) {
            var element1 = arr2[i]
            if (Number(element1.qid) === Number(row.qid) && Number(element1.qtype) === Number(row.qtype)) {
              element1.operation = 0
            }
          }
        }).catch(() => {
        })
      },
      creatRedeemCodeDetail (res) { // 详情回填
        this.basicInfo.cxcost = res.cxcost.toString() // 促销费用
        this.basicInfo.usertype = res.usertype.toString() // 客资类型
        this.basicInfo.startStopTime = [this.timeDeltSecond(res.startDate), this.timeDeltSecond(res.overDate)] // 兑换截止日期
        this.basicInfo.gysproportion = res.gysproportion // 供应商补差占比
        this.basicInfo.pcname = res.pcname // 批次名称
        // this.basicInfo.hqemail = res.hqemail // 邮箱
        this.basicInfo.remark = res.remark // 备注
        this.basicInfo.messageTitle = res.messageTitle // 标题
        this.basicInfo.messageContent = res.messageContent // 内容
        this.redeemCodeDetails = res.redeemCodeDetails
        for (var index = 0; index < res.redeemCodeDetails.length; index++) {
          var element = res.redeemCodeDetails[index]
          this.redeemCodeDetails[index].num = element.num
          this.redeemCodeDetails[index].expirationType = element.expirationType.toString()
          this.redeemCodeDetails[index].qtype = element.qtype.toString()
          // this.redeemCodeDetails[index].phpTicketId = element.phpTicketId
          if (element.expirationType === '1') {
            this.redeemCodeDetails[index].beginDate = this.timeDeltSecond(element.beginDate)
            this.redeemCodeDetails[index].endDate = this.timeDeltSecond(element.endDate)
          }
          if (element.expirationType === '2') {
            this.redeemCodeDetails[index].endDate = this.timeDeltSecond(element.endDate)
          }
          if (element.expirationType === '3') {
            this.redeemCodeDetails[index].daynum = element.daynum
          }
        }
        // console.log(this.redeemCodeDetails)
      },
      creatData (buttonType) { // 创建 提交 _data
        this.basicInfo.gysproportion = this.selectSalesCosts.type === 2 ? this.basicInfo.gysproportion : 0
        var dataInfo = {
          // branchName: this.branchName, // 旧分公司名称
          // deptName: this.deptName, // 部门名称
          bid: this.newBranchId, // 新分公司id
          branchId: this.basicInfo.branchId, // 旧分公司id
          dept: this.basicInfo.dept, // 部门id
          createBranchId: this.branchOrgId, // 创建人新公司ID
          createUser: this.userName, // 创建人 当前用户
          userId: this.userId,
          id: this.$store.state.tab.uid ? this.$store.state.tab.uid.id : '',
          state: buttonType, // 按钮类型 1 暂存 2 提交
          gwId: this.roleId, // 岗位ID
          uorId: this.uorId // 用户id
        }
        // console.log(this.redeemCodeDetails)
        var registerCpDetail = []
        for (var index = 0; index < this.redeemCodeDetails.length; index++) {
          var element = this.redeemCodeDetails[index]
          var redeemCodeDetailObj = {}
          redeemCodeDetailObj.num = element.num // 生成总张数
          redeemCodeDetailObj.qid = element.qid // 券id
          redeemCodeDetailObj.expirationType = Number(element.expirationType) // 有效期类型
          redeemCodeDetailObj.qtype = element.qtype // 优惠券类型
          redeemCodeDetailObj.phpTicketId = element.phpTicketId //
          if (Number(element.expirationType) === 1) {
            redeemCodeDetailObj.beginDate = element.beginDate
            redeemCodeDetailObj.endDate = element.endDate
            redeemCodeDetailObj.daynum = ''
          }
          if (Number(element.expirationType) === 2) {
            redeemCodeDetailObj.endDate = element.endDate
            redeemCodeDetailObj.daynum = ''
            redeemCodeDetailObj.beginDate = ''
          }
          if (Number(element.expirationType) === 3) {
            redeemCodeDetailObj.endDate = ''
            redeemCodeDetailObj.beginDate = ''
            redeemCodeDetailObj.daynum = element.daynum
          }
          registerCpDetail.push(redeemCodeDetailObj)
        }
        var _data = Object.assign(this.basicInfo, dataInfo)
        _data.registerCpDetail = registerCpDetail
        return _data
      },
      onSubmit (buttonType, formName) { // 提交
        this.$refs[formName].validate((valid) => {
          this.formValidation()
          var self = this
          console.log(this.couponValid)
          setTimeout(function () {
            if (valid && self.couponValid === true) {
              var _data = self.creatData(buttonType)
              // self.subDisable = true
              console.log(_data)
              activity.yhqhd.zcfq[self.isCreateOrUpdate](_data, (res) => {
                console.log(res)
                if (res.message === 'ok') {
                  self.cancel(self.menuId)
                  self.message(self.text + '成功', 'success')
                  // self.subDisable = false
                  self.$store.dispatch('zcfqState', self.$store.state.updateState.zcfqState + 1)
                } else if (res.code === -6) {
                  // self.subDisable = false
                  self.message(res.message, 'error')
                } else {
                  // self.subDisable = false
                  self.message(res.message, 'error')
                }
              })
            } else {
              return false
            }
          }, 100)
        })
      },
      formValidation () { // 提交表单验证
        if (this.redeemCodeDetails.length === 0) {
          this.couponValid = false
          this.message('优惠券不为空', 'error')
        } else {
          for (var index = 0; index < this.redeemCodeDetails.length; index++) {
            var element = this.redeemCodeDetails[index]
            if (Number(element.expirationType) === 1) {
              if ((element.beginDate !== '' && element.endDate !== '') && element.num !== '') {
                if (moment(element.beginDate).valueOf() >= moment(this.basicInfo.startDate).valueOf()) {
                  this.couponValid = true
                } else {
                  this.message('活动开始时间小于等于优惠券开始时间', 'error')
                  this.basicInfo.startStopTime = ''
                  this.couponValid = false
                }
              } else {
                this.message('第' + (index + 1) + '行有效期或每人/数量不为空/格式错误', 'error')
                this.couponValid = false
                break
              }
            }
            if (Number(element.expirationType) === 2) {
              if (element.endDate !== '' && element.num !== '') {
                if (moment(element.endDate).valueOf() > moment(this.basicInfo.startDate).valueOf()) {
                  this.couponValid = true
                } else {
                  this.message('活动开始时间小于优惠券结束时间', 'error')
                  this.basicInfo.startStopTime = ''
                  this.couponValid = false
                }
              } else {
                this.message('第' + (index + 1) + '行有效期或每人/数量不为空/格式错误', 'error')
                this.couponValid = false
                break
              }
            }
            if (Number(element.expirationType) === 3) {
              if (element.daynum !== '' && element.num !== '') {
                this.couponValid = true
              } else {
                this.message('第' + (index + 1) + '行有效期或每人/数量不为空/格式错误', 'error')
                this.couponValid = false
                break
              }
            }
          }
        }
      },
      pause () { // 暂存
      },
      cancel (id, num) { // 取消
        if (num) {
          this.$confirm('确定要取消？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('delTab', {id: id})
          }).catch(() => {
          })
        } else {
          this.$store.dispatch('delTab', {id: id})
        }
      },
      timeFormat (d, n) { // 时间格式化
        if (d && d !== '') {
          if (n === 'single') {
            this.basicInfo.expirationDate = d
          } else if (n === 'double') {
            return d.split(' - ')
          }
        }
      },
      timeDeltSecond (d) { // 时间去秒
        if (d) {
          return d.split(' ')[0]
        }
      },
      daterangeFormat (t) { // 时间段格式化
        if (t) {
          this.basicInfo.startDate = t[0]
          this.basicInfo.overDate = t[1]
        } else {
          this.basicInfo.startStopTime = []
          this.basicInfo.startDate = ''
          this.basicInfo.overDate = ''
        }
      },
      message (text, type) { // 消息提示
        this.$message({
          showClose: true,
          message: text,
          type: type
        })
      }
    },
    created () {
      this.menuId = this.$store.state.tab.menuId
      if (this.$store.state.tab.uid) {
        console.log(this.$store.state.tab)
        this.isCreateOrUpdate = 'update'
        this.text = '编辑'
        // this.pageLoading = true
        this.$store.dispatch('pageLoading', true)
        // this.searchSalesCosts(this.$store.state.tab.uid) // 查询促销费用
        this.searchDetail(this.$store.state.tab.uid)
        this.searchCustomerType() // 查询客资类型
        if (this.branchId === 1) {
          this.brachDisabled = false
        } else {
          this.brachDisabled = true
        }
      } else {
        this.isCreateOrUpdate = 'create'
        // this.showBranchName = this.branchName // 新增是公司是当前用户的公司名称
        // this.showDeptName = this.deptName // 新增是公司是当前用户的公司名称
        this.text = '新增'
        if (this.branchId === 1) {
          this.brachDisabled = false
          this.basicInfo.branchId = this.branchId
          this.basicInfo.dept = this.deptId
          this.newBranchId = this.branchOrgId
          // this.createBranchId = this.branchOrgId
        } else {
          this.brachDisabled = true
          this.showBranch = this.branchName
          this.showDept = this.deptName
          this.basicInfo.branchId = this.branchId
          this.basicInfo.dept = this.deptId
          this.newBranchId = this.branchOrgId
          // this.createBranchId = this.branchOrgId
          // this.formInline.branchId = this.branchId
        }
        this.searchSalesCosts() // 查询促销费用
        this.searchCustomerType() // 查询客资类型
      }
      // console.log(this.isAddOrUpdate)
    },
    computed: mapState({
      userName: function (state) {
        if (!state.user.info.user_name) {
          this.$store.dispatch('SET_TOKEN')
        }
        return state.user.info.user_name
      },
      userId: function (state) {
        return state.user.info.user_id
      },
      roleId: function (state) {
        return state.user.info.roleid
      },
      uorId: function (state) {
        return state.user.info.uor_id
      },
      branchName: function (state) {
        return state.user.info.branchId === 1 ? '总公司' : state.user.info.branchName
      },
      branchId: function (state) {
        return state.user.info.branchId
      },
      branchOrgId: function (state) {
        return state.user.info.branchOrgId
      },
      deptName: function (state) {
        return state.user.info.parOrgName
      },
      deptId: function (state) {
        return state.user.info.or_org_id
      }
    }),
    watch: {
      branchList (a, b) {
        this.getDeptList(this.basicInfo.branchId)
      }
    }
  }
</script>






